use serde::{Deserialize, Serialize};
use chrono::{DateTime, Utc};
use std::fs;
use std::path::PathBuf;
use tui::style::Color;
use crossterm::event::{self, Event};
use std::io;


// 常量定义
const DEPRESSION_HUNGER_THRESHOLD: i32 = 30;
const SLEEP_ENERGY_THRESHOLD: i32 = 20;
const WAKE_ENERGY_THRESHOLD: i32 = 40;
const MOOD_VERY_HAPPY_THRESHOLD: i32 = 80;
const MOOD_HAPPY_THRESHOLD: i32 = 60;
const MOOD_NORMAL_THRESHOLD: i32 = 40;
const MOOD_UNHAPPY_THRESHOLD: i32 = 20;

// 猫咪属性常量
pub const CAT_HAPPINESS_DECAY_BASE: i32 = 1;
pub const CAT_HUNGER_DECAY_BASE: i32 = 1;
pub const CAT_ENERGY_DECAY_BASE: i32 = 1;
pub const CAT_EXTRA_DECAY_EVERY_5MIN: i32 = 1;
pub const CAT_SLEEP_ENERGY_RECOVERY: i32 = 10;
pub const CAT_FEED_HAPPINESS: i32 = 20;
pub const CAT_FEED_HUNGER: i32 = 35;
pub const CAT_FEED_ENERGY: i32 = 20;
pub const CAT_PLAY_HAPPINESS: i32 = 50;
pub const CAT_PLAY_HUNGER: i32 = -10;
pub const CAT_PLAY_ENERGY: i32 = 20;

// 章鱼噼属性常量
pub const OCTOPUS_HAPPINESS_DECAY_AMOUNT: i32 = 1;  // 每次衰减的量
pub const OCTOPUS_HUNGER_DECAY_AMOUNT: i32 = 1;     // 每次衰减的量
pub const OCTOPUS_ENERGY_DECAY_AMOUNT: i32 = 1;     // 每次衰减的量
pub const OCTOPUS_SLEEP_ENERGY_RECOVERY: i32 = 5;
pub const OCTOPUS_FEED_HAPPINESS: i32 = 25;
pub const OCTOPUS_FEED_HUNGER: i32 = 50;
pub const OCTOPUS_FEED_ENERGY: i32 = 20;
pub const OCTOPUS_PLAY_HAPPINESS: i32 = 10;
pub const OCTOPUS_PLAY_HUNGER: i32 = 20;
pub const OCTOPUS_PLAY_ENERGY: i32 = 10;



// 心情状态枚举
#[derive(Debug, Clone, PartialEq)]
pub enum MoodState {
    VeryHappy,
    Happy,
    Normal,
    Unhappy,
    VeryUnhappy,
    Depressed,
    Sleeping,
}

// 宠物类型枚举
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum PetType {
    Cat(CatBreed),
    Octopus(OctopusType),
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum CatBreed {
    Orange,    // 大橘
    Cow,       // 奶牛
    Tabby,     // 狸花
    Black,     // 黑猫
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum OctopusType {
    Pink,      // 粉色章鱼噼
    Blue,      // 蓝色章鱼噼
    Purple,    // 紫色章鱼噼
}

impl OctopusType {
    pub fn get_name(&self) -> &'static str {
        match self {
            OctopusType::Pink => "粉色章鱼",
            OctopusType::Blue => "蓝色章鱼",
            OctopusType::Purple => "紫色章鱼",
        }
    }
    
    pub fn get_colors(&self) -> (Color, Color, Color) {
        match self {
            OctopusType::Pink => (Color::LightMagenta, Color::LightMagenta, Color::LightMagenta),
            OctopusType::Blue => (Color::LightBlue, Color::LightBlue, Color::LightBlue),
            OctopusType::Purple => (Color::Magenta, Color::Magenta, Color::Magenta),
        }
    }
    
    pub fn all() -> Vec<OctopusType> {
        vec![
            OctopusType::Pink,
            OctopusType::Blue,
            OctopusType::Purple,
        ]
    }
}

impl PetType {

}

impl CatBreed {
    pub fn get_colors(&self) -> (Color, Color, Color) {
        match self {
            CatBreed::Orange => (Color::Yellow, Color::White, Color::Red),
            CatBreed::Cow => (Color::White, Color::Black, Color::Magenta),
            CatBreed::Tabby => (Color::Yellow, Color::Gray, Color::Cyan),
            CatBreed::Black => (Color::Gray, Color::White, Color::Blue),
        }
    }
    
    pub fn get_name(&self) -> &'static str {
        match self {
            CatBreed::Orange => "大橘",
            CatBreed::Cow => "奶牛",
            CatBreed::Tabby => "狸花",
            CatBreed::Black => "黑猫",
        }
    }
    
    pub fn all() -> Vec<CatBreed> {
        vec![CatBreed::Orange, CatBreed::Cow, CatBreed::Tabby, CatBreed::Black]
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub struct PetStatus {
    pub happiness: i32,
    pub hunger: i32,
    pub energy: i32,
    pub last_interaction: DateTime<Utc>,
    pub last_update: DateTime<Utc>,
    pub is_sleeping: bool,
}

impl Default for PetStatus {
    fn default() -> Self {
        let now = Utc::now();
        Self {
            happiness: 50,
            hunger: 50,
            energy: 50,
            last_interaction: now,
            last_update: now,
            is_sleeping: false,
        }
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub struct PetConfig {
    pub name: String,
    pub pet_type: PetType,
    pub status: PetStatus,
    pub created_at: DateTime<Utc>,
    // 向后兼容字段
    #[serde(skip_serializing_if = "Option::is_none")]
    pub breed: Option<CatBreed>,
}

impl PetConfig {
    pub fn new(name: String, pet_type: PetType) -> Self {
        Self {
            name,
            pet_type,
            status: PetStatus::default(),
            created_at: Utc::now(),
            breed: None,
        }
    }
    
    // 向后兼容的构造函数

    
    pub fn get_config_path() -> PathBuf {
        PathBuf::from(".lilypet.json")
    }
    
    pub fn load() -> Option<Self> {
        let path = Self::get_config_path();
        if path.exists() {
            let content = fs::read_to_string(path).ok()?;
            serde_json::from_str(&content).ok()
        } else {
            None
        }
    }
    
    pub fn save(&self) -> Result<(), Box<dyn std::error::Error>> {
        let path = Self::get_config_path();
        let content = serde_json::to_string_pretty(self)?;
        fs::write(path, content)?;
        Ok(())
    }
    
    pub fn load_or_create() -> Result<Self, Box<dyn std::error::Error>> {
        if let Some(config) = Self::load() {
            Ok(config)
        } else {
            Self::create_new()
        }
    }
    
    pub fn create_new() -> Result<Self, Box<dyn std::error::Error>> {
        println!("🐱 欢迎来到 Lily Pat！");

        // 选择宠物类型
        println!("\n请选择你的宠物类型:");
        println!("1. 猫咪");
        println!("2. 章鱼噼");
        
        print!("请输入选择 (1-2): ");
        io::Write::flush(&mut io::stdout())?;
        let mut choice = String::new();
        io::stdin().read_line(&mut choice)?;
        
        let pet_type = match choice.trim() {
            "1" => PetType::Cat(CatBreed::Orange),
            "2" => PetType::Octopus(OctopusType::Pink),
            _ => return Err("无效的选择".into()),
        };
        
        let (final_pet_type, name) = match pet_type {
            PetType::Cat(_) => {
                // 选择猫咪品种
                println!("\n请选择猫咪的品种:");
                let breeds = CatBreed::all();
                for (i, breed) in breeds.iter().enumerate() {
                    println!("{}. {}", i + 1, breed.get_name());
                }
                
                print!("请输入选择 (1-4): ");
                io::Write::flush(&mut io::stdout())?;
                let mut choice = String::new();
                io::stdin().read_line(&mut choice)?;
                
                let choice: usize = choice.trim().parse().map_err(|_| "无效的选择")?;
                if choice < 1 || choice > breeds.len() {
                    return Err("选择超出范围".into());
                }
            
                let breed = breeds[choice - 1].clone();
                println!("\n让我们为你的小猫咪取个名字吧～");
                // 获取猫咪名字
                print!("请输入猫咪的名字: ");
                io::Write::flush(&mut io::stdout())?;
                let mut name = String::new();
                io::stdin().read_line(&mut name)?;
                let name = name.trim().to_string();
                
                if name.is_empty() {
                    return Err("名字不能为空".into());
                }
                
                println!("\n🎉 太好了！你的{} '{}' 已经准备好了！", breed.get_name(), name);
                (PetType::Cat(breed), name)
            },
            PetType::Octopus(_) => {
                // 选择章鱼噼类型
                println!("\n请选择章鱼噼的类型:");
                let octopus_types = OctopusType::all();
                for (i, octopus_type) in octopus_types.iter().enumerate() {
                    println!("{}. {}", i + 1, octopus_type.get_name());
                }
                
                print!("请输入选择 (1-3): ");
                io::Write::flush(&mut io::stdout())?;
                let mut choice = String::new();
                io::stdin().read_line(&mut choice)?;
                
                let choice: usize = choice.trim().parse().map_err(|_| "无效的选择")?;
                if choice < 1 || choice > octopus_types.len() {
                    return Err("选择超出范围".into());
                }
            
                let octopus_type = octopus_types[choice - 1].clone();
                println!("\n让我们为你的小章鱼噼取个名字吧～");
                // 获取章鱼噼名字
                print!("请输入章鱼噼的名字: ");
                io::Write::flush(&mut io::stdout())?;
                let mut name = String::new();
                io::stdin().read_line(&mut name)?;
                let name = name.trim().to_string();
                
                if name.is_empty() {
                    return Err("名字不能为空".into());
                }
                
                println!("\n🎉 太好了！你的{} '{}' 已经准备好了！", octopus_type.get_name(), name);
                (PetType::Octopus(octopus_type), name)
            }
        };
        
        println!("按任意键开始游戏...");
        
        
        // 等待用户按键
        crossterm::terminal::enable_raw_mode()?;
        loop {
            if let Event::Key(_) = event::read()? {
                break;
            }
        }
        crossterm::terminal::disable_raw_mode()?;
        
        let config = Self::new(name, final_pet_type);
        config.save()?;
        
        Ok(config)
    }
    
    pub fn update_status(&mut self, happiness_delta: i32, hunger_delta: i32, energy_delta: i32) {
        self.status.happiness = (self.status.happiness + happiness_delta).clamp(1, 100);
        self.status.hunger = (self.status.hunger + hunger_delta).clamp(1, 100);
        self.status.energy = (self.status.energy + energy_delta).clamp(1, 100);
        self.status.last_interaction = Utc::now();
        
        // 检查是否需要睡眠
        self.check_sleep_state();
    }
    
    pub fn update_time_decay(&mut self) {
        let now = Utc::now();
        let minutes_passed = (now - self.status.last_update).num_minutes();
        
        if minutes_passed >= 1 {
            let decay_cycles = minutes_passed as i32;
            
            // 根据宠物类型获取衰减率和睡眠恢复率
            let (happiness_decay, hunger_decay, energy_decay, sleep_energy_recovery) = match self.pet_type {
                PetType::Cat(_) => {
                    // 猫咪每分钟基础衰减，每5分钟额外衰减
                    let extra_decay = (decay_cycles / 5) * CAT_EXTRA_DECAY_EVERY_5MIN;
                    
                    let happiness_decay = CAT_HAPPINESS_DECAY_BASE * decay_cycles + extra_decay;
                    let hunger_decay = CAT_HUNGER_DECAY_BASE * decay_cycles + extra_decay;
                    let energy_decay = CAT_ENERGY_DECAY_BASE * decay_cycles + extra_decay;
                    
                    // println!("猫咪衰减: 心情-{}, 饥饿-{}, 精力-{}, 额外-{}, 经过{}分钟", 
                    //     happiness_decay, hunger_decay, energy_decay, extra_decay, minutes_passed);
                    
                    (
                        happiness_decay,
                        hunger_decay,
                        energy_decay,
                        CAT_SLEEP_ENERGY_RECOVERY
                    )
                },
                PetType::Octopus(_) => {
                    // 章鱼噼每分钟25%概率衰减，使用时间戳确保一致性
                    let mut total_happiness_decay = 0;
                    let mut total_hunger_decay = 0;
                    let mut total_energy_decay = 0;
                    
                    for minute_offset in 0..decay_cycles {
                        // 使用时间戳+分钟偏移作为伪随机种子，确保衰减的一致性
                        let seed = (self.status.last_update.timestamp() + minute_offset as i64) as u64;
                        
                        // 25%概率衰减 (seed % 4 == 0 给出25%概率)
                        if seed % 4 == 0 {
                            total_happiness_decay += OCTOPUS_HAPPINESS_DECAY_AMOUNT;
                            total_hunger_decay += OCTOPUS_HUNGER_DECAY_AMOUNT;
                            total_energy_decay += OCTOPUS_ENERGY_DECAY_AMOUNT;
                        }
                    }
                    
                    // println!("章鱼噼衰减: 心情-{}, 饥饿-{}, 精力-{}, 经过{}分钟", 
                    //     total_happiness_decay, total_hunger_decay, total_energy_decay, minutes_passed);
                    
                    (
                        total_happiness_decay,
                        total_hunger_decay,
                        total_energy_decay,
                        OCTOPUS_SLEEP_ENERGY_RECOVERY
                    )
                }
            };
            
            
            if self.status.is_sleeping {
                // 睡眠时能量恢复，但饥饿和心情仍然衰减
                self.status.energy = (self.status.energy + sleep_energy_recovery * decay_cycles).clamp(1, 100);
                self.status.hunger = (self.status.hunger - hunger_decay * decay_cycles).clamp(1, 100);
                self.status.happiness = (self.status.happiness - happiness_decay * decay_cycles).clamp(1, 100);
            } else {
                // 正常状态下所有属性都衰减
                self.status.happiness = (self.status.happiness - happiness_decay * decay_cycles).clamp(1, 100);
                self.status.hunger = (self.status.hunger - hunger_decay * decay_cycles).clamp(1, 100);
                self.status.energy = (self.status.energy - energy_decay * decay_cycles).clamp(1, 100);
            }
            
            self.status.last_update = now;
            self.check_sleep_state();
        }
    }
    
    fn check_sleep_state(&mut self) {
        // 能量低于阈值时进入睡眠状态
        if self.status.energy < SLEEP_ENERGY_THRESHOLD {
            self.status.is_sleeping = true;
        } else if self.status.energy >= WAKE_ENERGY_THRESHOLD {
            // 能量恢复到阈值以上时醒来
            self.status.is_sleeping = false;
        }
    }
    
    // 公共方法用于强制检查睡眠状态
    pub fn force_check_sleep_state(&mut self) {
        self.check_sleep_state();
    }
    
    pub fn can_move(&self) -> bool {
        !self.status.is_sleeping && self.status.hunger >= DEPRESSION_HUNGER_THRESHOLD
    }
    
    pub fn can_play(&self) -> bool {
        !self.status.is_sleeping
    }
    
    pub fn get_mood_state(&self) -> MoodState {
        if self.status.is_sleeping {
            return MoodState::Sleeping;
        }
        
        if self.status.hunger < DEPRESSION_HUNGER_THRESHOLD {
            return MoodState::Depressed;
        }
        
        let avg = (self.status.happiness + self.status.hunger + self.status.energy) / 3;
        match avg {
            x if x >= MOOD_VERY_HAPPY_THRESHOLD => MoodState::VeryHappy,
            x if x >= MOOD_HAPPY_THRESHOLD => MoodState::Happy,
            x if x >= MOOD_NORMAL_THRESHOLD => MoodState::Normal,
            x if x >= MOOD_UNHAPPY_THRESHOLD => MoodState::Unhappy,
            _ => MoodState::VeryUnhappy,
        }
    }
    
    pub fn get_mood(&self) -> &'static str {
        match self.get_mood_state() {
            MoodState::Sleeping => "睡觉中",
            MoodState::Depressed => "垂头丧气",
            MoodState::VeryHappy => "非常开心",
            MoodState::Happy => "开心",
            MoodState::Normal => "一般",
            MoodState::Unhappy => "有点不开心",
            MoodState::VeryUnhappy => "很不开心",
        }
    }
    

    
    // Debug功能 - 可通过条件编译轻松移除
    #[cfg(feature = "debug")]
    pub fn debug_set_status(&mut self, field: &str, value: i32) -> bool {
        let success = match field {
            "happiness" => {
                self.status.happiness = value.clamp(0, 100);
                true
            },
            "hunger" => {
                self.status.hunger = value.clamp(0, 100);
                true
            },
            "energy" => {
                self.status.energy = value.clamp(0, 100);
                // 设置能量后立即检查睡眠状态
                self.check_sleep_state();
                true
            },
            _ => false
        };
        
        // 更新最后交互时间
        if success {
            self.status.last_interaction = Utc::now();
        }
        
        success
    }
}